import Peer from "peerjs";
// import networkConfiguration from "@/network/configuration";
import usePeerStore from "@/store/peer";
import useUserStore from "@/store/user";

import { showToast } from "vant";

export default {
    install(app) {
        app.config.globalProperties.$initializePeer = new Promise(resolve => {
            let peerStore = usePeerStore();
            let userStore = useUserStore();


            /* let { host, port, path } = { ...networkConfiguration.server.peerServer };
            let localPeer = new Peer({ host, port, path }); */
            let localPeer = new Peer();

            localPeer.on("connection", dataConnection => {
                if (peerStore.dataConnection) {
                    dataConnection.on("open", () => {
                        dataConnection.send({
                            instruction: peerStore.instruction.busy
                        });
                    });
                } else {
                    dataConnection.on("data", data => {
                        //请求通话
                        if (data.instruction === peerStore.instruction.request) {
                            peerStore.dataConnection = dataConnection;
                            //激活通知
                            peerStore.activateNotification = true;
                        }

                        //对方取消
                        else if (data.instruction === peerStore.instruction.cancel) {
                            //关闭数据连接
                            peerStore.dataConnection.close();
                            peerStore.dataConnection = undefined;
                            //取消激活通知
                            peerStore.activateNotification = false;
                        }

                        //对方挂断
                        else if (data.instruction === peerStore.instruction.ringOff) {
                            //关闭数据连接
                            peerStore.dataConnection.close();
                            peerStore.dataConnection = undefined;
                            //关闭媒体连接
                            peerStore.mediaConnection.close();
                            peerStore.mediaConnection = undefined;
                        }
                    });
                }
            });

            localPeer.on("call", mediaConnection => {
                peerStore.mediaConnection = mediaConnection;
            });

            localPeer.on("disconnected", () => {
                localPeer.reconnect();
                showToast("网络连接中断，请检查网络连接");
            });

            localPeer.on("error", error => {
                console.error("localPeer error,the error information is : ", JSON.stringify(error));
                showToast("网络连接中断，请检查网络连接");
            });

            localPeer.on("open", localPeerId => {
                peerStore.localPeer = localPeer;
                userStore.setPeerJsId(localPeerId)
                resolve();
            });
        });
    }
}